#include "utils/autofile.hpp"
#include <stdio.h>

shared_ptr<autofile> autofile::read_file(const string filename)
{
	shared_ptr<autofile> p{new autofile(filename)};
	p->read_content();
	return p;
}

autofile::autofile(const string filename_)
{
	open = false;
	filename = filename_;
	fp = nullptr;
	content = nullptr;
	length = 0;
}

autofile::~autofile()
{
	if (fp) {
		fclose(fp);
	}

	if (content) {
		delete[] content;
	}
}

bool autofile::is_open()
{
	return open;
}

void autofile::read_content()
{
	fp = fopen(filename.c_str(), "r");
	if (fp) {
		open = true;

		fseek(fp, 0, SEEK_END);
		length = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		content = new char[length + 1];
		int read_chars = fread(content, sizeof(char), length, fp);
		content[read_chars] = 0;
	} else {
		perror(filename.c_str());
	}
}

char *autofile::get_str()
{
	return content;
}
